/*
 * Copyright 2009 The Microlog project @sourceforge.net
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.sf.microlog.android.appender;

import java.io.File;
import java.io.IOException;

import net.sf.microlog.common.appender.AbstractFileAppender;
import android.content.Context;

/**
 * The <code>FileAppender</code> class is used for file logging on the Android
 * platform.
 * 
 * @author Johan Karlsson (johan.karlsson@jayway.se)
 * @since 2.0
 * 
 */
public class FileAppender extends AbstractFileAppender {

	private Context context;

	private File file;

	private String fileURI;

	/**
	 * @return the context
	 */
	public Context getContext() {
		return context;
	}

	/**
	 * Set the <code>Context</code> to be used when creating the log file.
	 * 
	 * @param context
	 *            the context to set
	 */
	public void setContext(Context context) {
		this.context = context;
	}

	/**
	 * @see net.sf.microlog.common.appender.AbstractFileAppender#clear()
	 */
	@Override
	public void clear() {
		// TODO
	}

	/**
	 * @see net.sf.microlog.common.appender.AbstractFileAppender#getLogSize()
	 */
	@Override
	public long getLogSize() {
		long size = SIZE_UNDEFINED;

		if (file != null && file.exists()) {
			size = file.length();
		}

		return size;
	}

	/**
	 * @see net.sf.microlog.common.appender.AbstractFileAppender#createFileURI()
	 */
	@Override
	protected String createFileURI() {
		String fileURI = DEFAULT_FILENAME;

		if (fileName != null) {
			fileURI = fileName;
		}

		return fileURI;
	}

	/**
	 * 
	 * @see net.sf.microlog.common.appender.AbstractFileAppender#createFile(java.lang.String)
	 */
	@Override
	protected void createFile(String fileURI) throws IOException {
		// We only store the fileURI on the Android platform. The file is
		// created when the
		// OutputStream is created.
		this.fileURI = fileURI;
	}

	/**
	 * @see net.sf.microlog.common.appender.AbstractFileAppender#openOutputStream()
	 */
	@Override
	protected synchronized void openOutputStream() throws IOException {
		outputStream = context.openFileOutput(fileURI,
				Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
	}

	@Override
	public void close() throws IOException {
		if (logOpen) {
			if (outputStream != null) {
				outputStream.close();
			}

			logOpen = false;
		}
	}

}
